<div class="row">
	<div class="col-xs-12">
		<div class="box">
			<div class="box-header">
				<h3 class="box-title">角色管理</h3>
				<div class="box-tools">
					<div class="input-group input-group-sm" style="width: 350px;">
						<input type="text" name="table_search" id="searchNameId"
							class="form-control pull-right" placeholder="角色名">
						<div class="input-group-btn">
							<button type="button" class="btn btn-default btn-search">
                                <i class="fa fa-search"></i>
							</button>
							<button type="button" class="btn btn-default btn-add">添加</button>
							<button type="button" class="btn btn-default btn-update">修改</button>
						</div>
					</div>
				</div>
			</div>
			<!-- /.box-header -->
			<div class="box-body table-responsive no-padding">
				<form>
				  <table class="table table-hover">
					<thead>
						<tr>
						    <th>ID</th>
							<th>角色名称</th>
							<th>角色描述</th>
							<th>创建用户</th>
							<th>修改用户</th>
							<th>创建时间</th>
							<th>修改时间</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody id="tbodyId">
					</tbody>
				  </table>
				</form>
			</div>
			<!-- /.box-body -->
			<div id="pageId" class="box-footer clearfix">
            </div>
		</div>
		<!-- /.box -->
	</div>
</div>
<script type="text/javascript">
   $(function(){
	   $("#pageId").load("/modules/common/page.html",doGetObjects);
	  $(".input-group-btn")
	  .on("click",".btn-search",doQueryObjects)
	  .on("click",".btn-add,.btn-update",doLoadEditUI)
	  $("#tbodyId")
	  .on("click",".btn-valid",doDeleteById)
   });

   function doLoadEditUI(){
	   let title;
	   if($(this).hasClass('btn-add')){
		   title="角色添加";
		   doLoadPageUI(title);
	   }else{
		   let id = doGetCheckedId();
		   if (!id) {	//如果没选择用户
			   alert("请先选择");
			   return;
		   }
		   title="角色修改"
		   let url=`${baseUrl}/shoppingback/role/${id}`;
		   $.ajax({url:url,crossDomain:true,xhrFields:{withCredentials: true},
			   headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
			   success(result){
			   if(result.success){
				   if(result.status==401){
					   alert(result.msg);
					   return;
				   }
				   if(result.status==403){
					   alert(result.msg);
					   return;
				   }
				  result.data.id=id;//在结果中动态追加id
				  $("#mainContentId").data("data",result.data);
				  doLoadPageUI(title);//异步加载页面  
			   }else{
				  alert(result.message); 
			   }
		   }});
	   }
   }
   function doLoadPageUI(title){
	   let url="/modules/sys/role_edit.html"
	   $("#mainContentId")
	   .load(url,function(){
		   $(".box-title").html(title);
	   })
   }
   function doQueryObjects(){
	   $("#pageId").data("pageNum",1);
	   doGetObjects();
   }
   function doGetObjects(){
	   let pageNum = $("#pageId").data("pageNum");
	   if (!pageNum) pageNum = 1;
	   let params = {"pageNum": pageNum}
	   params.query = $("#searchNameId").val().trim();
	   let url=`${baseUrl}/shoppingback/role`;
	   $.ajax({url:url,data:params,crossDomain:true,xhrFields:{withCredentials:true},
		   headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
		   success(result){
			   if(result.status==401){
				   alert(result.msg);
				   return;
			   }
			   if(result.status==403){
				   alert(result.msg);
				   return;
			   }
			   doHandleResponseResult(result);
		   }
	   });
   }
   //点击id选择用户
   function doGetCheckedId() {
	   return $("tbody input[name='radioId']:checked").val();
   }
   function doHandleResponseResult(result){
	   
	   if(result.success){
		  doSetTableBodyRows(result.data.rows);
		  doSetPagination(result.data);//page.html
	   }else{
		  doSetTableBodyErrors(result.message);
	   }
   }
   function doSetTableBodyErrors(message){
	   //获取body对象并清空
	   let tBody=$("#tbodyId");
	   tBody.empty();
	   //创建tr对象
	   let tr=$("<tr></tr>");
	   //创建td对象
	   let len=$("table th").length;
	   let td=$("<td></td>");
	   td.prop("colspan",len);
	   td.append(message);
	   tr.append(td);
	   //将tr追加到tbody
	   tBody.append(tr);
   }
   function doSetTableBodyRows(records){
	  //获取tbody对象,并清空
	   let tBody=$("#tbodyId");
	   tBody.empty();
	   //2.迭代数据,并追加到tBody
	   records.forEach((item,i)=>{
		  //2.1构建tr对象
		  let tr=$("<tr></tr>");
		  tr.data("id",item.id);
		  //2.2构建tds对象
		  let tds=doCreateTds(item,i);
		  //2.3将tds对象追加到tr中
		  tr.append(tds);
		  //2.4将tr追加到tbody中
		  tBody.append(tr);
	   })
   }
   function doCreateTds(row,i){
	   return `<td><input type='radio' name='radioId' value='${row.id}' ></td>>
	   <td>${row.name}</td>
       <td>${row.remark}</td>
       <td>${row.createdUser}</td>
       <td>${row.modifiedUser}</td>
       <td>${getFormatDate2(row.createTime)}</td>
       <td>${getFormatDate2(row.updateTime)}</td>
       <td><button type='button' class='btn btn-default btn-valid'>删除</button></td>`;
   }
   //删除按钮
   function doDeleteById() {
	   if (!confirm("确定删除?")) {
		   return;
	   }
	   let id=$(this).parents("tr").data("id");
	   let url = `${baseUrl}/shoppingback/role/${id}`;  /*  ../${newValid} */
	   console.log("url", url)
	   let btn = $(this);//获取点击的button对象
	   console.log("token", window.localStorage.getItem("accessToken"));
	   $.ajax({
		   method: "delete",
		   url: url,
		   headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
		   crossDomain: true,
		   xhrFields: {withCredentials: true},

		   success(result) {
			   if(result.state==403){
				   alert(result.message);
				   return;
			   }
			   if (result.success) {
				   alert(result.msg);
				   doGetObjects();
				   // doEditRow(btn,rowData.valid);
			   } else {
				   alert(result.msg);
			   }
		   }
	   });
   }

   function getFormatDate2() {
	   var nowDate = new Date();
	   var year = nowDate.getFullYear();
	   var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
	   var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
	   var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
	   var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
	   var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
	   return year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
   }
</script>
